package com.zhang.shopcar.utils;

import android.content.Context;

import com.zhang.shopcar.dialog.CustomProgressDialog;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

/**
 * 作者：junj
 * 时间：2016/8/12
 * 描述：TOTO
 */
public abstract class RxSubscribe<T> extends Subscriber<T> {
    private boolean showDialog = true;
    private Context mContext;
    private String msg;
    private CustomProgressDialog progressDialog = null;

    /**
     * @param context context
     * @param msg     dialog message
     */
    public RxSubscribe(Context context, String msg) {
        this.mContext = context;
        this.msg = msg;
    }

    /**
     * @param context context
     */
    public RxSubscribe(Context context) {
        this(context, "加载中");
    }

    public RxSubscribe(Context context, boolean showDailog) {
        this(context, "加载中");
        this.showDialog = showDailog;
    }

    @Override
    public void onCompleted() {
        if (showDialog)
           stopProgressDialog();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (showDialog) {
            startProgressDialog();
        }
    }

    @Override
    public void onNext(T t) {
        if (showDialog)
            stopProgressDialog();
        _onNext(t);
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        if (e instanceof SocketTimeoutException) {
            _onError("网络中断，请检查您的网络状态");
        } else if (e instanceof ConnectException) {
            _onError(e.getMessage());
        } else if (e instanceof HttpException) {
            HttpException e1 = (HttpException) e;

                _onError(e1.message());

        } else {
            _onError("请求失败，请稍后再试...");
        }
        if (showDialog)
         stopProgressDialog();
    }
    private void startProgressDialog(){
        if (progressDialog == null){
            progressDialog = CustomProgressDialog.createDialog(mContext);
        }

        progressDialog.show();
    }

    private void stopProgressDialog(){
        if (progressDialog != null){
            progressDialog.dismiss();
            progressDialog = null;
        }
    }
    protected abstract void _onNext(T t);

    protected abstract void _onError(String message);
}
